package org.example.projecttwo.security;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.projecttwo.service.Icommon.IRedisService;
import org.example.projecttwo.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.NonNull;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * <p>
 * JWT认证过滤器
 * </p>
 *
 * <p>
 * 用于拦截HTTP请求，从请求头中解析JWT Token并进行身份验证
 * </p>
 *
 * @author nn
 * @since 2025-11-01
 */
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private IRedisService redisService;

    /**
     * 日志记录器
     */
    private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationFilter.class);

    /**
     * 过滤器核心方法，对每个HTTP请求进行JWT Token验证
     *
     * @param request HTTP请求
     * @param response HTTP响应
     * @param chain 过滤器链
     * @throws ServletException Servlet异常
     * @throws IOException IO异常
     */
    @Override
    protected void doFilterInternal(@NonNull HttpServletRequest request,
                                    @NonNull HttpServletResponse response,
                                    @NonNull FilterChain chain) throws ServletException, IOException {

        final String header = request.getHeader("Authorization");

        String jwt = null;
        String userId = null;

        // 从请求头中提取JWT Token
        if (header != null && header.startsWith("Bearer ")) {
            jwt = header.substring(7);
            try {
                userId = jwtUtil.getUserIdFromToken(jwt).toString(); // 从JWT中提取userId
            } catch (Exception e) {
                logger.warn("JWT 解析失败: {}", e.getMessage());
            }
        }

        // 验证并设置用户认证信息
        if (userId != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            // 检查token是否在黑名单中
            if (isTokenBlacklisted(jwt)) {
                logger.warn("Token在黑名单中: {}", truncateToken(jwt));
            } else {
                UserDetails userDetails = this.userDetailsService.loadUserByUsername(userId);
                if (jwtUtil.validateToken(jwt, Long.valueOf(userId))) {
                    UsernamePasswordAuthenticationToken authToken =
                            new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                    authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    SecurityContextHolder.getContext().setAuthentication(authToken);
                }
            }
        }

        chain.doFilter(request, response);
    }

    /**
     * 检查token是否在黑名单中
     *
     * @param token JWT token
     * @return 是否在黑名单中
     */
    private boolean isTokenBlacklisted(String token) {
        String blacklistKey = "blacklist:" + token;
        return redisService.hasKey(blacklistKey);
    }

    /**
     * 截取token的前几部分用于日志记录，避免日志过长
     *
     * @param token 完整的JWT token
     * @return 截取后的token
     */
    private String truncateToken(String token) {
        if (token == null || token.isEmpty()) {
            return token;
        }

        // JWT由三部分组成，用"."分隔，我们只需要显示前两部分即可
        String[] parts = token.split("\\.");
        if (parts.length >= 2) {
            return parts[0] + "." + parts[1];
        }
        // 如果不是标准JWT格式，返回前30个字符
        return token.length() > 30 ? token.substring(0, 30) : token;
    }
}